package data

import (
    "utils"
    "strconv"
    "helper/redisclient"
)

type Cache struct {
    rc      *redisclient.RedisClient
}

func NewCache() *Cache {
    ca := new(Cache)
    if ca == nil {
        return nil
    }
    rc := redisclient.NewRedisClient(map[string]string{"host": "127.0.0.1:6379"}, 1000, 1000, 1000, 256, 256, 86400)
    if rc == nil {
        return nil
    }
    ca.rc = rc
    return ca
}

func (ca *Cache) GetSecKillFlag(userid string) bool {
    err := ca.rc.Setnx(userid, "1")
    if err != nil {
        return false
    } else {
        return true
    }
}

func (ca *Cache) GetUserKill(userid, productid string) (string, error) {
    key := utils.StringConn([]string {productid, "orders"}, "_")
    value, err := ca.rc.HGet(key, userid)
    if err != nil {
        return "", err
    } else {
        return value, nil
    }
}

func (ca *Cache) GetProductKill(productid string) (map[string]string, error) {
    key := utils.StringConn([]string {productid, "orders"}, "_")
    value, err := ca.rc.HGetall(key)
    if err != nil {
        return nil, err
    } else {
        return value, nil
    }
}

func (ca *Cache) GetSecKillEnd(productid string) bool {
    key := utils.StringConn([]string {productid, "end"}, "_")
    _, err := ca.rc.Get(key)
    if err != nil {
        return false
    }
    return true
}

func (ca *Cache) GetProductCnt(productid string) (int, error) {
    key := utils.StringConn([]string {productid, "remain"}, "_")
    value, err := ca.rc.Get(key)
    if err != nil {
        return 0, err
    } else if value == "0" {
        return -1, err
    }
    cnt, err := strconv.Atoi(value)
    if err != nil {
        return -1, err
    }
    return cnt, nil
}

func (ca *Cache) SetProductCnt(productid string, cnt int) error {
    key := utils.StringConn([]string {productid, "remain"}, "_")
    value := strconv.Itoa(cnt)
    err := ca.rc.Set(key, value)
    if err != nil {
        return err
    }
    return nil
}

func (ca *Cache) SetSuccOrder(productid, userid string, cnt int) error {
    key := utils.StringConn([]string {productid, "orders"}, "_")
    value := strconv.Itoa(cnt)
    err := ca.rc.HSet(key, userid, value)
    if err != nil {
        return err
    }
    return nil
}

func (ca *Cache) SetSecKillEnd(productid string) error {
    key := utils.StringConn([]string {productid, "end"}, "_")
    err := ca.rc.Set(key, "1")
    if err != nil {
        return err
    }
    return nil
}
